<template>
  <el-card class="member-list-card" shadow="never">
    <template #header>
      <div class="card-header">
        <div class="header-left">
          <span>{{ $t('team.teamMembers') }}</span>
          <el-tag v-if="members.length > 0" type="info" size="small">
            {{ members.length }} 个成员
          </el-tag>
          <el-tag
            v-if="teamStore.teamOnlineStats"
            type="success"
            size="small"
            :icon="Switch"
          >
            {{ teamStore.teamOnlineStats.onlineMembers }} 在线
          </el-tag>
        </div>
        <div class="header-actions">
          <el-dropdown
            v-if="canManage && selectedMembers.length > 0"
            split-button
            type="danger"
            size="small"
            @click="handleBatchRemove"
          >
            <el-icon><Delete /></el-icon>
            批量移除 ({{ selectedMembers.length }})
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="showBatchRoleChangeDialog = true">
                  <el-icon><Edit /></el-icon>
                  批量角色变更
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <el-button
            :icon="Refresh"
            size="small"
            @click="refreshMembers"
            :loading="teamStore.memberLoading"
          >
            {{ $t('common.refresh') }}
          </el-button>
          <el-button
            :icon="Switch"
            size="small"
            @click="refreshOnlineStatus"
            :loading="teamStore.onlineStatusLoading"
            type="success"
          >
            刷新在线状态
          </el-button>
        </div>
      </div>
    </template>

    <div class="member-list" v-loading="teamStore.memberLoading">
      <div v-if="members.length === 0" class="empty-state">
        <el-empty :description="$t('team.noMembers')" />
      </div>
      
      <div v-else class="member-grid">
        <div 
          v-for="member in members" 
          :key="member.id"
          class="member-item"
        >
          <div class="member-selection" v-if="canManage && canRemoveMember(member)">
            <el-checkbox
              v-model="selectedMembers"
              :label="member.userId"
              @change="handleMemberSelect"
            />
          </div>

          <div class="member-avatar">
            <el-badge
              is-dot
              :type="memberOnlineStatus[member.userId] ? 'success' : 'danger'"
              :hidden="false"
            >

              <el-avatar
                :size="48"
                :src="member.avatarUrl"
                :icon="UserFilled"
              >
                {{ member.nickname?.charAt(0) || member.username?.charAt(0) }}
              </el-avatar>
            </el-badge>
          </div>
          
          <div class="member-info">
            <div class="member-name">
              {{ member.nickname || member.username || `用户${member.userId}` }}
            </div>
            <div class="member-meta">
              <el-tag 
                :type="getMemberRoleType(member.role)" 
                size="small"
              >
                {{ getMemberRoleLabel(member.role) }}
              </el-tag>
              <span class="join-time">
                {{ $t('team.joinedAt') }} {{ formatDate(member.joinedAt) }}
              </span>
            </div>
          </div>

          <div class="member-actions" v-if="canManage && canOperateMember(member)">
            <el-dropdown trigger="click" @command="(cmd: string) => handleMemberCommand(cmd, member)">
              <el-button :icon="MoreFilled" circle size="small" />
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    command="changeRole"
                    :icon="Edit"
                    v-if="canChangeRole(member)"
                  >
                    {{ $t('team.changeRole') }}
                  </el-dropdown-item>
                  <el-dropdown-item 
                    command="transfer" 
                    :icon="Switch"
                    v-if="canTransferOwnership(member)"
                    divided
                  >
                    {{ $t('team.transferOwnership') }}
                  </el-dropdown-item>
                  <el-dropdown-item 
                    command="remove" 
                    :icon="Delete"
                    v-if="canRemoveMember(member)"
                    divided
                  >
                    {{ $t('team.removeMember') }}
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>
  </el-card>

  <!-- 角色变更对话框 -->
  <ChangeRoleDialog
    v-model="showChangeRoleDialog"
    :member="selectedMemberForRole"
    :current-user-role="currentUserRole"
    @confirm="handleRoleChangeConfirm"
  />



  <!-- 批量角色变更对话框 -->
  <BatchRoleChangeDialog
    v-model="showBatchRoleChangeDialog"
    :selected-members="getSelectedMembersData"
    :current-user-role="currentUserRole"
    @confirm="handleBatchRoleChangeConfirm"
  />
</template>

<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  User,
  Edit,
  Refresh,
  UserFilled,
  MoreFilled,
  Switch,
  Delete
} from '@element-plus/icons-vue'
import { useTeamStore } from '@/stores/teamStore'
import { useAuthStore } from '@/stores/auth'
import { teamApi } from '@/api/team'
import type { TeamMember } from '@/types/team'
import ChangeRoleDialog from './ChangeRoleDialog.vue'
import BatchRoleChangeDialog from './BatchRoleChangeDialog.vue'
import { 
  getMemberRoleLabel, 
  getMemberRoleType,
  canUpdateMemberRole,
  canRemoveMembers
} from '@/types/team'
import { formatDate } from '@/utils/date'

interface Props {
  teamId: number
  canManage: boolean
}

interface Emits {
  (e: 'member-updated'): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()
const { t } = useI18n()

const teamStore = useTeamStore()
const authStore = useAuthStore()

// 计算属性
const members = computed(() => teamStore.teamMembers)
const selectedMembers = ref<number[]>([])
const showChangeRoleDialog = ref(false)

// 确保selectedMembers始终是数组
watch(selectedMembers, (newVal) => {
  if (!Array.isArray(newVal)) {
    selectedMembers.value = []
  }
}, { immediate: true })
const selectedMemberForRole = ref<TeamMember | null>(null)
const showBatchRoleChangeDialog = ref(false)
const onlineStatusTimer = ref<NodeJS.Timeout | null>(null)

/**
 * 团队成员在线状态数据
 * 键为用户ID，值为在线状态（true=在线，false=离线）
 */
const memberOnlineStatus = ref<Record<number, boolean>>({})

const currentUserRole = computed(() => {
  // 根据当前用户ID获取在团队中的角色
  const currentUserId = authStore.user?.id
  if (!currentUserId) return 'MEMBER'

  const currentMember = members.value.find(member => member.userId === currentUserId)
  return currentMember?.role || 'MEMBER'
})

// 方法
const refreshMembers = async () => {
  try {
    await teamStore.fetchTeamMembers(props.teamId)
    // 同时刷新在线状态
    await refreshOnlineStatus()
  } catch (error) {
    console.error('刷新成员列表失败:', error)
  }
}

/**
 * 刷新团队成员在线状态
 * 从后端API获取最新的成员在线状态数据，并更新本地响应式状态
 */
const refreshOnlineStatus = async () => {
  try {
    // 调用API获取团队成员在线状态
    const response = await teamApi.getTeamMembersOnlineStatus(props.teamId)

    // 验证响应数据结构
    if (response && response.data && response.data.members && Array.isArray(response.data.members)) {
      // 清空旧的在线状态数据
      memberOnlineStatus.value = {}

      // 遍历成员列表，更新在线状态
      response.data.members.forEach((member) => {
        if (member.userId && typeof member.isOnline === 'boolean') {
          memberOnlineStatus.value[member.userId] = member.isOnline
        }
      })
    }
  } catch (error) {
    console.error('获取团队成员在线状态失败:', error)
  }
}

/**
 * 启动在线状态自动刷新
 * 立即刷新一次在线状态，然后每30秒自动刷新一次
 */
const startOnlineStatusAutoRefresh = () => {
  // 清除现有定时器，避免重复创建
  if (onlineStatusTimer.value) {
    clearInterval(onlineStatusTimer.value)
  }

  // 立即刷新一次在线状态
  refreshOnlineStatus()

  // 设置定时器，每30秒自动刷新在线状态
  onlineStatusTimer.value = setInterval(() => {
    refreshOnlineStatus()
  }, 30000)
}

/**
 * 停止在线状态自动刷新
 * 清除定时器，释放资源
 */
const stopOnlineStatusAutoRefresh = () => {
  if (onlineStatusTimer.value) {
    clearInterval(onlineStatusTimer.value)
    onlineStatusTimer.value = null
  }
}

const canOperateMember = (member: TeamMember) => {
  // 不能操作自己
  if (member.userId === authStore.user?.id) return false
  // 只有管理员以上权限才能操作成员
  return props.canManage
}

const canChangeRole = (member: TeamMember) => {
  // 不能修改自己的角色，不能修改所有者角色（除非自己是所有者）
  const currentUserId = authStore.user?.id
  if (member.userId === currentUserId) return false
  if (member.role === 'OWNER' && currentUserRole.value !== 'OWNER') return false

  // 检查是否有权限修改角色
  return canUpdateMemberRole(currentUserRole.value, 'ADMIN') ||
         canUpdateMemberRole(currentUserRole.value, 'MEMBER')
}

const canTransferOwnership = (member: TeamMember) => {
  return currentUserRole.value === 'OWNER' && member.role !== 'OWNER'
}

const canRemoveMember = (member: TeamMember) => {
  return canRemoveMembers(currentUserRole.value) && member.role !== 'OWNER'
}

const handleMemberCommand = async (command: string, member: TeamMember) => {
  try {
    switch (command) {
      case 'changeRole':
        selectedMemberForRole.value = member
        showChangeRoleDialog.value = true
        break
      case 'transfer':
        await handleTransferOwnership(member)
        break
      case 'remove':
        await handleRemoveMember(member)
        break
    }
  } catch (error) {
    console.error('操作成员失败:', error)
  }
}

// 处理角色变更确认
const handleRoleChangeConfirm = async (member: TeamMember, newRole: string) => {
  try {
    await teamStore.updateMemberRole(props.teamId, member.userId, { role: newRole as 'ADMIN' | 'MEMBER' | 'OWNER' })
    ElMessage.success(t('team.roleChangeSuccess'))
    showChangeRoleDialog.value = false
    selectedMemberForRole.value = null
    emit('member-updated')
  } catch (error: any) {
    console.error('角色变更失败:', error)
    ElMessage.error(error?.response?.data?.message || '角色变更失败')
  }
}

const handleTransferOwnership = async (member: TeamMember) => {
  await ElMessageBox.confirm(
    t('team.transferOwnershipConfirm', { name: member.nickname || member.username || `用户${member.userId}` }),
    t('team.transferOwnership'),
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
      dangerouslyUseHTMLString: true,
      message: `
        <div style="margin: 16px 0;">
          <p style="margin-bottom: 8px; color: #E6A23C;">⚠️ 重要提醒：</p>
          <p style="margin-bottom: 4px;">• 转移后您将失去团队所有权</p>
          <p style="margin-bottom: 4px;">• 您的角色将变更为管理员</p>
          <p style="margin-bottom: 4px;">• 此操作不可撤销</p>
        </div>
        <p>确定要将所有权转移给 <strong>${member.nickname || member.username || `用户${member.userId}`}</strong> 吗？</p>
      `
    }
  )

  await teamStore.transferOwnership(props.teamId, member.userId)
  ElMessage.success(t('team.transferSuccess'))
  emit('member-updated')
}

const handleRemoveMember = async (member: TeamMember) => {
  await ElMessageBox.confirm(
    `确定要将 ${member.nickname || member.username || `用户${member.userId}`} 移出团队吗？`,
    '移除成员',
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
      dangerouslyUseHTMLString: true,
      message: `
        <div style="margin: 16px 0;">
          <p style="margin-bottom: 8px; color: #E6A23C;">⚠️ 移除成员后：</p>
          <p style="margin-bottom: 4px;">• 该成员将失去团队访问权限</p>
          <p style="margin-bottom: 4px;">• 该成员的团队数据将被保留</p>
          <p style="margin-bottom: 4px;">• 可以通过邀请码重新加入</p>
        </div>
        <p>确定要移除 <strong>${member.nickname || member.username || `用户${member.userId}`}</strong> 吗？</p>
      `
    }
  )

  await teamStore.removeTeamMember(props.teamId, member.userId)
  ElMessage.success(t('team.removeMemberSuccess'))
  emit('member-updated')
}

// 批量操作
const handleMemberSelect = () => {
  // 复选框变化时的处理，selectedMembers会自动更新
}

const handleBatchRemove = async () => {
  if (selectedMembers.value.length === 0) return

  await ElMessageBox.confirm(
    `确定要移除选中的 ${selectedMembers.value.length} 个成员吗？`,
    '批量移除成员',
    {
      confirmButtonText: t('common.confirm'),
      cancelButtonText: t('common.cancel'),
      type: 'warning',
      dangerouslyUseHTMLString: true,
      message: `
        <div style="margin: 16px 0;">
          <p style="margin-bottom: 8px; color: #E6A23C;">⚠️ 批量移除后：</p>
          <p style="margin-bottom: 4px;">• 选中的成员将失去团队访问权限</p>
          <p style="margin-bottom: 4px;">• 成员的团队数据将被保留</p>
          <p style="margin-bottom: 4px;">• 可以通过邀请码重新加入</p>
        </div>
        <p>确定要移除选中的 <strong>${selectedMembers.value.length}</strong> 个成员吗？</p>
      `
    }
  )

  // 批量移除成员
  const promises = selectedMembers.value.map(userId =>
    teamStore.removeTeamMember(props.teamId, userId)
  )

  await Promise.all(promises)

  // 清空选择
  selectedMembers.value = []

  ElMessage.success(`成功移除 ${promises.length} 个成员`)
  emit('member-updated')
}

// 获取选中成员的完整数据
const getSelectedMembersData = computed(() => {
  return members.value.filter(member => selectedMembers.value.includes(member.userId))
})

// 处理批量角色变更确认
const handleBatchRoleChangeConfirm = async (membersToChange: TeamMember[], newRole: string) => {
  try {
    // 批量更新成员角色
    const promises = membersToChange.map(member =>
      teamStore.updateMemberRole(props.teamId, member.userId, { role: newRole as 'ADMIN' | 'MEMBER' | 'OWNER' })
    )

    await Promise.all(promises)

    // 清空选择
    selectedMembers.value = []
    showBatchRoleChangeDialog.value = false

    ElMessage.success(`成功变更 ${membersToChange.length} 个成员角色`)
    emit('member-updated')

  } catch (error: any) {
    console.error('批量角色变更失败:', error)
    ElMessage.error('批量角色变更失败: ' + (error?.message || '未知错误'))
  }
}

/**
 * 组件挂载时的初始化操作
 * 1. 刷新成员列表
 * 2. 启动在线状态自动刷新
 */
onMounted(() => {
  refreshMembers()
  startOnlineStatusAutoRefresh()
})

/**
 * 组件卸载时的清理操作
 * 停止在线状态自动刷新，释放定时器资源
 */
onUnmounted(() => {
  stopOnlineStatusAutoRefresh()
})
</script>

<style scoped lang="scss">
.member-list-card {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-left {
      display: flex;
      align-items: center;
      gap: 12px;
    }

    .header-actions {
      display: flex;
      gap: 8px;
    }
  }

  .member-list {
    .empty-state {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 200px;
    }

    .member-grid {
      display: grid;
      gap: 16px;

      .member-item {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 16px;
        background: var(--el-bg-color-page);
        border-radius: 8px;
        border: 1px solid var(--el-border-color-lighter);
        transition: all 0.3s ease;

        &:hover {
          border-color: var(--el-color-primary-light-5);
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .member-selection {
          flex-shrink: 0;
          margin-right: 8px;
        }

        .member-avatar {
          flex-shrink: 0;
        }

        .member-info {
          flex: 1;
          min-width: 0;

          .member-name {
            font-size: 16px;
            font-weight: 500;
            color: var(--el-text-color-primary);
            margin-bottom: 4px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }

          .member-meta {
            display: flex;
            align-items: center;
            gap: 8px;

            .join-time {
              font-size: 12px;
              color: var(--el-text-color-secondary);
            }
          }
        }

        .member-actions {
          flex-shrink: 0;
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 768px) {
  .member-list-card {
    .card-header {
      flex-direction: column;
      gap: 12px;
      align-items: flex-start;

      .header-actions {
        width: 100%;
        justify-content: flex-end;
      }
    }

    .member-list {
      .member-grid {
        .member-item {
          .member-info {
            .member-meta {
              flex-direction: column;
              align-items: flex-start;
              gap: 4px;
            }
          }
        }
      }
    }
  }
}
</style>
